<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      display: flex;
    }

    .box div {
      width: 200px;
      height: 110px;
      background-color: red;
      transition: all 0.5s;
      color: #fff;
      text-align: center;

      margin-left: 10px;
    }

    .box div p {
      margin: 0px;
      padding: 0px;
    }

    .button-box {
      margin-top: 20px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
  </div>
  <div class="button-box">
    <!-- <button data-key="name">姓名</button> -->
    <button data-key="age">年龄</button>
    <!-- <button data-key="gender">性别</button> -->
    <!-- <button data-key="class">班级</button> -->
    <button data-key="score">成绩</button>
  </div>
</body>
<script>
  let studentList = [{
    name: '张三',
    age: 18,
    gender: '男',
    class: '1班',
    score: 90,
    change: 0
  }, {
    name: '李四',
    age: 19,
    gender: '男',
    class: '2班',
    score: 80,
    change: 0
  }, {
    name: '王五',
    age: 20,
    gender: '女',
    class: '2班',
    score: 70,
    change: 0
  }, {
    name: '赵六',
    age: 21,
    gender: '女',
    class: '1班',
    score: 60,
    change: 0
  }]
  create(studentList)
  function create(list) {
    const box = document.querySelector('.box')
    box.innerHTML = list.map((item, index) => {
      return `<div ${item.change != 0 ? style = `style="transform: translateX(${item.change}px)"` : ""}><p>${item.name}</p><p>${item.age}</p><p>${item.gender}</p><p>${item.class}</p><p>${item.score}</p></div>`
    }).join('')
    setTimeout(() => {
      const box = document.querySelector('.box')
      for (let i = 0; i < box.children.length; i++) {
        const element = box.children[i]
        element.style.transform = 'translateX(0px)'
        console.dir(element)
      }
    }, 50)
  }

  const buttonBox = document.getElementsByClassName('button-box')[0]
  buttonBox.addEventListener('click', (e) => {
    const index = e.target.index
    const oldList = studentList
    const newList = sort(JSON.parse(JSON.stringify(oldList)), e.target.dataset.key)
    newList.forEach((item, index) => {
      oldList.forEach((value, key) => {
        if (item.name === value.name)
          item.change = (key - index) * 210
      })
    })

    create(newList)
    console.log(oldList, newList)
    studentList = newList
  })
  function sort(list, key) {
    return list.sort((a, b) => +a[key] - +b[key])
  }
</script>

</html>